import requests
import json
import sys
 
# 配置你的Gitee账号的access token
access_token = '42f7e0d444e98c7a0ac4a93c2b7fbf75'

# 使用Gitee提供的API，例如获取用户的所有仓库
headers = {
    'Authorization': 'token ' + access_token
}


branch_list = []
commit_list = []
date = sys.argv[1]

since_time = "%s-01" % date
until_time = "%s-31" % date

### 获取分支
currpage = 1

while True:
    api_url_branch_cantian = "https://gitee.com/api/v5/repos/openeuler/cantian-connector-mysql/branches?sort=name&direction=asc&page=%s&per_page=20" % (currpage)
    response = requests.get(api_url_branch_cantian, headers=headers)
    if response.status_code == 200:
        repositories = response.json()
        if not repositories:
            break
        for res in repositories:
            branch_list.append(res["name"])
        currpage += 1
    else:
        print('Error:', response.status_code)

if 'master' in branch_list:
    branch_list.remove('master')
print("cantian-connector-mysql branch: %s" % branch_list)

### 获取所有提交sha
print("begin to get commits")
for branch in branch_list:
    print("getting commits from %s......" % branch)
    currpage = 1

    while True:
        api_url_commit_connector = "https://gitee.com/api/v5/repos/openeuler/cantian-connector-mysql/commits?sha=%s&since=%s&until=%s&page=%s&per_page=20" % (branch, since_time, until_time, currpage)
        response = requests.get(api_url_commit_connector, headers=headers)
        if response.status_code == 200:
            repositories = response.json()
            if not repositories:
                break
            for res in repositories:
                commit_list.append(res["sha"])
            currpage += 1
        else:
            print('Error:', response.status_code)
            exit(1)
        
    # print(commit_list)

mysql_connector_data_list = {}

print("calculating code......")
for one_commit in commit_list:
    
    api_url_one_commit = "https://gitee.com/api/v5/repos/openeuler/cantian-connector-mysql/commits/%s" % one_commit
    response = requests.get(api_url_one_commit, headers=headers)
    if response.status_code == 200:
        res = response.json()
        add_code = res["stats"]["additions"]
        delete_code = res["stats"]["deletions"]
        user_name = res["commit"]["author"]["name"]
        user_data = mysql_connector_data_list.get(user_name, [0, 0])
        user_data[0] += add_code
        user_data[1] += delete_code
        mysql_connector_data_list[user_name] = user_data

mysql_connector_list = []
for key in mysql_connector_data_list:
    mysql_connector_list.append({"name":key, "additions":mysql_connector_data_list[key][0], "deletions":mysql_connector_data_list[key][1]})
mysql_connector_list.sort(key = lambda x: x['additions'], reverse=True)
with open("stat/%s/mysql_connector_code_stat.json" % date, "w") as f:
    json.dump(mysql_connector_list, f, indent=4)